<?php
/**
 * 游戏相关API
 * 处理游戏列表、游戏进度等功能
 */

require_once __DIR__ . '/ApiHandler.php';

class GameApi extends ApiHandler {
    
    /**
     * 处理GET请求
     * 获取游戏列表或游戏详情
     */
    protected function GET() {
        $action = $this->getParam('action', 'list');
        
        switch ($action) {
            case 'list':
                $this->getGameList();
                break;
            case 'detail':
                $this->getGameDetail();
                break;
            case 'progress':
                $this->getGameProgress();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
                break;
        }
    }
    
    /**
     * 处理POST请求
     * 保存游戏进度
     */
    protected function POST() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $action = $this->getParam('action', '');
        
        switch ($action) {
            case 'save_progress':
                $this->saveGameProgress();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
                break;
        }
    }
    
    /**
     * 获取游戏列表
     */
    private function getGameList() {
        $ageGroup = $this->getParam('age_group', '');
        $categoryId = (int)$this->getParam('category_id', 0);
        $isPremium = $this->getParam('is_premium', null);
        
        $params = [];
        $where = "g.is_active = 1";
        
        if ($ageGroup) {
            $where .= " AND (g.age_group = ? OR g.age_group = 'all')";
            $params[] = $ageGroup;
        }
        
        if ($categoryId > 0) {
            $where .= " AND g.category_id = ?";
            $params[] = $categoryId;
        }
        
        if ($isPremium !== null) {
            $where .= " AND g.is_premium = ?";
            $params[] = (int)$isPremium;
        }
        
        $sql = "SELECT g.*, c.name as category_name, c.description as category_description 
                FROM " . DB_PREFIX . "games g
                JOIN " . DB_PREFIX . "game_categories c ON g.category_id = c.id
                WHERE {$where} 
                ORDER BY g.category_id ASC, g.display_order ASC, g.name ASC";
        
        $games = $this->db->fetchAll($sql, $params);
        
        // 获取每个游戏关联的技能
        foreach ($games as &$game) {
            $sql = "SELECT s.id, s.name, s.description, s.icon, gs.weight
                    FROM " . DB_PREFIX . "skills s
                    JOIN " . DB_PREFIX . "game_skills gs ON s.id = gs.skill_id
                    WHERE gs.game_id = ?
                    ORDER BY gs.weight DESC";
            
            $skills = $this->db->fetchAll($sql, [$game['id']]);
            $game['skills'] = $skills;
            
            // 如果用户已登录，获取该游戏的用户进度
            if ($this->user->isLoggedIn()) {
                $userId = $this->user->getUserId();
                
                $sql = "SELECT * FROM " . DB_PREFIX . "user_game_progress 
                        WHERE user_id = ? AND game_id = ?";
                $progress = $this->db->fetchRow($sql, [$userId, $game['id']]);
                
                if ($progress) {
                    $game['user_progress'] = $progress;
                }
            }
        }
        
        $this->sendResponse([
            'success' => true,
            'games' => $games
        ]);
    }
    
    /**
     * 获取游戏详情
     */
    private function getGameDetail() {
        // 验证必填参数
        if (!$this->validateRequiredParams(['game_id'])) {
            return;
        }
        
        $gameId = (int)$this->getParam('game_id');
        
        // 获取游戏信息
        $sql = "SELECT g.*, c.name as category_name, c.description as category_description 
                FROM " . DB_PREFIX . "games g
                JOIN " . DB_PREFIX . "game_categories c ON g.category_id = c.id
                WHERE g.id = ? AND g.is_active = 1";
        
        $game = $this->db->fetchRow($sql, [$gameId]);
        
        if (!$game) {
            $this->sendResponse([
                'success' => false,
                'message' => '游戏不存在或已禁用'
            ], 404);
            return;
        }
        
        // 获取游戏技能
        $sql = "SELECT s.id, s.name, s.description, s.icon, gs.weight
                FROM " . DB_PREFIX . "skills s
                JOIN " . DB_PREFIX . "game_skills gs ON s.id = gs.skill_id
                WHERE gs.game_id = ?
                ORDER BY gs.weight DESC";
        
        $skills = $this->db->fetchAll($sql, [$gameId]);
        $game['skills'] = $skills;
        
        // 如果用户已登录，获取游戏进度
        if ($this->user->isLoggedIn()) {
            $userId = $this->user->getUserId();
            
            $sql = "SELECT * FROM " . DB_PREFIX . "user_game_progress 
                    WHERE user_id = ? AND game_id = ?";
            $progress = $this->db->fetchRow($sql, [$userId, $gameId]);
            
            if ($progress) {
                $game['user_progress'] = $progress;
            }
        }
        
        $this->sendResponse([
            'success' => true,
            'game' => $game
        ]);
    }
    
    /**
     * 获取游戏进度
     */
    private function getGameProgress() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $userId = $this->user->getUserId();
        $gameId = (int)$this->getParam('game_id', 0);
        
        $where = "ugp.user_id = ?";
        $params = [$userId];
        
        if ($gameId > 0) {
            $where .= " AND ugp.game_id = ?";
            $params[] = $gameId;
        }
        
        $sql = "SELECT ugp.*, g.name as game_name, g.thumbnail, g.url, g.age_group
                FROM " . DB_PREFIX . "user_game_progress ugp
                JOIN " . DB_PREFIX . "games g ON ugp.game_id = g.id
                WHERE {$where}
                ORDER BY ugp.last_played_at DESC";
        
        $progress = $this->db->fetchAll($sql, $params);
        
        $this->sendResponse([
            'success' => true,
            'progress' => $progress
        ]);
    }
    
    /**
     * 保存游戏进度
     */
    private function saveGameProgress() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        // 验证必填参数
        if (!$this->validateRequiredParams(['game_id', 'score', 'stars'])) {
            return;
        }
        
        $userId = $this->user->getUserId();
        $gameId = (int)$this->getParam('game_id');
        $score = (int)$this->getParam('score');
        $stars = (int)$this->getParam('stars');
        $completionTime = (int)$this->getParam('completion_time', 0);
        
        // 验证游戏是否存在
        $sql = "SELECT * FROM " . DB_PREFIX . "games WHERE id = ? AND is_active = 1";
        $game = $this->db->fetchRow($sql, [$gameId]);
        
        if (!$game) {
            $this->sendResponse([
                'success' => false,
                'message' => '游戏不存在或已禁用'
            ], 404);
            return;
        }
        
        // 检查用户是否已有该游戏的进度记录
        $sql = "SELECT * FROM " . DB_PREFIX . "user_game_progress 
                WHERE user_id = ? AND game_id = ?";
        $existingProgress = $this->db->fetchRow($sql, [$userId, $gameId]);
        
        $now = date('Y-m-d H:i:s');
        $updated = false;
        
        try {
            if ($existingProgress) {
                // 更新记录，只有更高的分数和星级才会更新
                $updateData = [
                    'last_played_at' => $now,
                    'attempts' => $existingProgress['attempts'] + 1,
                    'updated_at' => $now
                ];
                
                if ($score > $existingProgress['score']) {
                    $updateData['score'] = $score;
                }
                
                if ($stars > $existingProgress['stars']) {
                    $updateData['stars'] = $stars;
                }
                
                if ($completionTime > 0 && ($existingProgress['completion_time'] == 0 || $completionTime < $existingProgress['completion_time'])) {
                    $updateData['completion_time'] = $completionTime;
                }
                
                $this->db->update('user_game_progress', $updateData, 'id = ?', [$existingProgress['id']]);
                $progressId = $existingProgress['id'];
                $updated = true;
            } else {
                // 创建新记录
                $data = [
                    'user_id' => $userId,
                    'game_id' => $gameId,
                    'score' => $score,
                    'stars' => $stars,
                    'completion_time' => $completionTime,
                    'attempts' => 1,
                    'last_played_at' => $now,
                    'created_at' => $now,
                    'updated_at' => $now
                ];
                
                $progressId = $this->db->insert('user_game_progress', $data);
            }
            
            // 更新用户技能
            $this->updateUserSkills($userId, $gameId, $score, $stars);
            
            // 检查成就解锁
            $this->checkAchievements($userId, $gameId, $stars);
            
            $this->sendResponse([
                'success' => true,
                'message' => $updated ? '游戏进度已更新' : '游戏进度已保存',
                'progress_id' => $progressId
            ]);
        } catch (PDOException $e) {
            $this->sendResponse([
                'success' => false,
                'message' => '保存游戏进度失败'
            ], 500);
        }
    }
    
    /**
     * 更新用户技能
     * @param int $userId 用户ID
     * @param int $gameId 游戏ID
     * @param int $score 得分
     * @param int $stars 星级
     */
    private function updateUserSkills($userId, $gameId, $score, $stars) {
        // 获取游戏关联的技能
        $sql = "SELECT skill_id, weight FROM " . DB_PREFIX . "game_skills WHERE game_id = ?";
        $gameSkills = $this->db->fetchAll($sql, [$gameId]);
        
        if (empty($gameSkills)) {
            return;
        }
        
        // 从设置中获取技能提升所需的进度点数
        $sql = "SELECT setting_value FROM " . DB_PREFIX . "settings WHERE setting_key = 'level_threshold'";
        $levelThreshold = (int)$this->db->fetchOne($sql);
        if ($levelThreshold <= 0) {
            $levelThreshold = 100; // 默认值
        }
        
        // 根据星级计算技能点数增加量
        $skillPointsPerStar = 10; // 默认值
        $sql = "SELECT setting_value FROM " . DB_PREFIX . "settings WHERE setting_key = 'points_per_star'";
        $pointsPerStar = $this->db->fetchOne($sql);
        if ($pointsPerStar) {
            $skillPointsPerStar = (int)$pointsPerStar;
        }
        
        $gainedPoints = $stars * $skillPointsPerStar;
        
        foreach ($gameSkills as $skill) {
            $skillId = $skill['skill_id'];
            $weight = $skill['weight'];
            
            // 技能权重越高，获得的技能点数越多
            $skillPoints = $gainedPoints * ($weight / 3); // 权重范围1-3
            
            // 检查用户是否已有该技能的记录
            $sql = "SELECT * FROM " . DB_PREFIX . "user_skills WHERE user_id = ? AND skill_id = ?";
            $userSkill = $this->db->fetchRow($sql, [$userId, $skillId]);
            
            $now = date('Y-m-d H:i:s');
            
            if ($userSkill) {
                // 更新用户技能
                $newProgress = $userSkill['progress'] + $skillPoints;
                $newLevel = $userSkill['level'];
                
                // 检查是否升级
                while ($newProgress >= $levelThreshold) {
                    $newProgress -= $levelThreshold;
                    $newLevel++;
                }
                
                $this->db->update('user_skills', [
                    'level' => $newLevel,
                    'progress' => $newProgress,
                    'updated_at' => $now
                ], 'id = ?', [$userSkill['id']]);
            } else {
                // 创建新的用户技能记录
                $newProgress = $skillPoints;
                $newLevel = 0;
                
                // 检查是否升级
                while ($newProgress >= $levelThreshold) {
                    $newProgress -= $levelThreshold;
                    $newLevel++;
                }
                
                $this->db->insert('user_skills', [
                    'user_id' => $userId,
                    'skill_id' => $skillId,
                    'level' => $newLevel,
                    'progress' => $newProgress,
                    'updated_at' => $now
                ]);
            }
        }
    }
    
    /**
     * 检查成就解锁
     * @param int $userId 用户ID
     * @param int $gameId 游戏ID
     * @param int $stars 星级
     */
    private function checkAchievements($userId, $gameId, $stars) {
        // 获取游戏信息
        $sql = "SELECT * FROM " . DB_PREFIX . "games WHERE id = ?";
        $game = $this->db->fetchRow($sql, [$gameId]);
        
        if (!$game) {
            return;
        }
        
        // 检查"初次探索"成就
        $sql = "SELECT a.id FROM " . DB_PREFIX . "achievements a 
                WHERE a.name = '初次探索' AND a.is_active = 1 
                AND NOT EXISTS (
                    SELECT 1 FROM " . DB_PREFIX . "user_achievements ua 
                    WHERE ua.user_id = ? AND ua.achievement_id = a.id
                )";
        $firstGameAchievementId = $this->db->fetchOne($sql, [$userId]);
        
        if ($firstGameAchievementId) {
            $this->db->insert('user_achievements', [
                'user_id' => $userId,
                'achievement_id' => $firstGameAchievementId,
                'achieved_at' => date('Y-m-d H:i:s')
            ]);
        }
        
        // 检查游戏特定成就（例如"记忆大师"）
        if ($game['name'] === '记忆卡牌' && $stars === 3) {
            $sql = "SELECT a.id FROM " . DB_PREFIX . "achievements a 
                    WHERE a.name = '记忆大师' AND a.is_active = 1 
                    AND NOT EXISTS (
                        SELECT 1 FROM " . DB_PREFIX . "user_achievements ua 
                        WHERE ua.user_id = ? AND ua.achievement_id = a.id
                    )";
            $memoryMasterAchievementId = $this->db->fetchOne($sql, [$userId]);
            
            if ($memoryMasterAchievementId) {
                $this->db->insert('user_achievements', [
                    'user_id' => $userId,
                    'achievement_id' => $memoryMasterAchievementId,
                    'achieved_at' => date('Y-m-d H:i:s')
                ]);
            }
        }
        
        // 检查"拼图能手"成就
        if ($game['category_id'] == 2) { // 拼图游戏分类
            // 获取所有拼图游戏ID
            $sql = "SELECT id FROM " . DB_PREFIX . "games WHERE category_id = 2 AND is_active = 1";
            $puzzleGames = $this->db->fetchAll($sql);
            $puzzleGameIds = array_column($puzzleGames, 'id');
            
            // 检查用户是否完成了所有拼图游戏
            $completedAll = true;
            foreach ($puzzleGameIds as $puzzleGameId) {
                $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "user_game_progress 
                        WHERE user_id = ? AND game_id =?";
                $completed = $this->db->fetchOne($sql, [$userId, $puzzleGameId]);
                
                if (!$completed) {
                    $completedAll = false;
                    break;
                }
            }
            
            if ($completedAll) {
                $sql = "SELECT a.id FROM " . DB_PREFIX . "achievements a 
                        WHERE a.name = '拼图能手' AND a.is_active = 1 
                        AND NOT EXISTS (
                            SELECT 1 FROM " . DB_PREFIX . "user_achievements ua 
                            WHERE ua.user_id = ? AND ua.achievement_id = a.id
                        )";
                $puzzleMasterAchievementId = $this->db->fetchOne($sql, [$userId]);
                
                if ($puzzleMasterAchievementId) {
                    $this->db->insert('user_achievements', [
                        'user_id' => $userId,
                        'achievement_id' => $puzzleMasterAchievementId,
                        'achieved_at' => date('Y-m-d H:i:s')
                    ]);
                }
            }
        }
    }
}

// 创建API实例并处理请求
$api = new GameApi('games');
$api->processRequest(); 